package com.yzg.simple.netty.dubbo.netty;

import com.yzg.simple.netty.dubbo.specification.TransferMethod;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author misterWei
 * @create 2020年01月10号:00点04分
 * @mailbox mynameisweiyan@gmail.com
 * <p>
 * 客户端调用关系
 */
public class NettyRpcClient {
    //首先创建好该Handler
    private NettyRpcClientHandler handler = null;
    //定义线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private String hostName;
    private int port;

    public NettyRpcClient(String hostName, int port) {
        this.hostName = hostName;
        this.port = port;
    }

    public Object getNames(final Class<?> calss) {

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{calss}, (proxy, method, args) -> {

            //初始化该信息
            if (Objects.isNull(handler)) {
                initLink();
            }
            //然后参数传递
            handler.setParms(TransferMethod.LIMIT+args[0]);
            //执行方法 的call 方法
            Object call = executorService.submit(handler).get();
            return call;

        });
    }

    //初始化该信息 千万记住 这是个方法 执行后千万别把 EventLoopGroup 关闭了
    public void initLink() {
        handler = new NettyRpcClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(handler);
                        }
                    });
            bootstrap.connect(this.hostName, this.port).sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
/*
            group.shutdownGracefully();
*/
        }
    }
}
